<template>
  <div>
    <div>
      <CategorySelector :disable="attrListFlag === false"></CategorySelector>
    </div>
    <el-card style="margin-top: 20px" v-if="attrListFlag">
      <template #header>
        <el-button
          type="primary"
          icon="ele-Plus"
          @click="addAttrButto()"
          :disabled="category3Id === ''"
          >添加属性</el-button
        >
      </template>
      <el-table :data="arrtInfoList">
        <el-table-column
          type="index"
          label="序号"
          width="100"
        ></el-table-column>
        <el-table-column
          label="属性名称"
          width="100"
          prop="attrName"
        ></el-table-column>
        <el-table-column label="属性名称列表">
          <template #="{ row }">
            <el-tag
              style="margin-right: 10px"
              type="success"
              v-for="attrValue in row.attrValueList"
              :key="attrValue.id"
              >{{ attrValue.valueName }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column width="200" label="修改">
          <template #="{ row }">
            <el-button
              type="warning"
              icon="ele-Edit"
              @click="addAttrButto(row)"
            ></el-button>
            <el-popconfirm title="是否删除" @confirm="delAttrItem(row.id)">
              <template #reference>
                <el-button type="danger" icon="ele-Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card v-else style="margin-top: 20px">
      <el-form inline>
        <el-form-item label="属性名">
          <el-input
            v-model="updateAttr!.attrName"
            clearable
            @blur="addHeaderInput"
            @keydown.enter="addHeaderInput"
            ref="addHeaderRef"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div>
        <div>
          <el-button type="primary" @click="addAttrValueButton"
            >添加属性值</el-button
          >
          <el-button @click="attrListFlag = true">取消</el-button>
        </div>
      </div>
      <div>
        <el-table :data="updateAttr!.attrValueList" style="margin: 20px 0">
          <el-table-column label="序号" width="100" type="index">
          </el-table-column>
          <el-table-column label="属性名称"
            ><template #="{ row }"
              ><span v-if="attrTemporary != row" @click="showInput(row)"
                >{{ row.valueName }}
              </span>
              <el-input
                v-else
                ref="valueNameRef"
                v-model="row.valueName"
                @blur="lostAttrTemporary(row)"
                @keydown.enter="lostAttrTemporary(row)" /></template
          ></el-table-column>

          <el-table-column width="150" label="操作">
            <template #="{ row }">
              <el-button
                type="danger"
                icon="ele-Delete"
                @click="removeAttr(row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div>
        <el-button
          type="primary"
          @click="saveHandler"
          :disabled="
            updateAttr!.attrValueList.length === 0 ||
            updateAttr!.attrName === ''
          "
          >保存</el-button
        >
        <el-button @click="attrListFlag = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>
<script lang="ts">
import { defineComponent, nextTick } from "vue";
import { reqAttrInfoList, reqUpdateAttr, reqDelAttrItem } from "@/api/attr";
import getCategoryStore from "@/stores/category";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: "Attr",
});
</script>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { ref, watch } from "vue";
import CategorySelector from "@/components/CategorySelector/index.vue";
import type { attrInfoType, attrValueListType } from "@/api/category";
import type { IAddOrEditAttrType } from "@/api/attr";
import { cloneDeep } from "lodash";
const categoryStore = getCategoryStore();
const { category1Id, category2Id, category3Id } = storeToRefs(categoryStore);
const arrtInfoList = ref<attrInfoType[]>([]);
//是否显示列表ref
const attrListFlag = ref(true);
//更新保存ref
const updateAttr = ref<IAddOrEditAttrType>();
//获取头部ref
const addHeaderRef = ref<HTMLInputElement>();
//获取子表单输入框ref
const valueNameRef = ref<HTMLInputElement>();
//临时attrValueList响应式数据
const attrTemporary = ref<Partial<attrValueListType>>();
//是否重复

//获取列表函数
const getAttrInfo = async () => {
  if (category3Id.value === "") return (arrtInfoList.value = []);

  try {
    arrtInfoList.value = await reqAttrInfoList(
      category1Id.value as number,
      category2Id.value as number,
      category3Id.value as number
    );
    console.log("category3Id.value as number", category3Id.value as number);
  } catch (e) {
    ElMessage.warning("获取失败");
  }
};
//监听
watch(category3Id, getAttrInfo, { immediate: true });
//删除按钮
const delAttrItem = async (id: number) => {
  try {
    await reqDelAttrItem(id);
    getAttrInfo();
    ElMessage.warning("删除成功");
  } catch (e) {
    ElMessage.warning("删除失败");
  }
};
//添加属性按钮
const addAttrButto = (data?: IAddOrEditAttrType) => {
  attrListFlag.value = false;
  if (!data) {
    //1、初始化数据

    updateAttr.value = {
      categoryId: category3Id.value as number,
      categoryLevel: 3,
      attrName: "",
      attrValueList: [],
    };
  } else {
    updateAttr.value = cloneDeep(data);
  }
};

//更新保存函数

//2//添加属性值
const addAttrValueButton = () => {
  // if ((updateAttr.value as IAddOrEditAttrType).attrName) {

  // }
  let data = {
    valueName: "",
  };
  if (updateAttr.value!.attrName === "") return;
  updateAttr.value?.attrValueList.push(data);
  attrTemporary.value = data;
  nextTick(() => {
    valueNameRef.value?.focus();
  });
};
// 1-1判断是否存在重复
const addHeaderInput = () => {
  // const isExist = updateAttr.value!.attrValueList.find(
  //   (attr) => updateAttr.value?.attrName == attr.valueName
  // );
  console.log(
    "attr.attrName == updateAttr.value!.attrName",
    updateAttr.value!.attrName
  );

  const isExist = arrtInfoList.value.find(
    (attr) =>
      attr.attrName == updateAttr.value!.attrName &&
      attr.id != updateAttr.value!.id
  );
  console.log("isExist", isExist);
  if (isExist) {
    ElMessage.warning("已存在");
    updateAttr.value!.attrName = "";

    nextTick(() => {
      addHeaderRef.value?.focus();
    });
  }
};
//3、保存
const saveHandler = async () => {
  try {
    if (updateAttr.value) {
      console.log("updateAttr.value", updateAttr.value);

      console.log("updateAttr.value", updateAttr.value);

      await reqUpdateAttr(updateAttr.value);
      ElMessage.success("更新成功");
      attrListFlag.value = true;
      getAttrInfo();
    }
  } catch (e) {
    ElMessage.warning("保存失败");
  }
};
// 4、点击显示表单元素
const showInput = (row: attrValueListType) => {
  attrTemporary.value = row;
  nextTick(() => {
    valueNameRef.value?.focus();
  });
};
//5、失去焦点

const lostAttrTemporary = (row: attrValueListType) => {
  // if (row.valueName == "") {
  //   removeAttr(row);
  // }
  if (attrTemporary.value == undefined && row.valueName) return;
  // console.log("111111");

  console.log(attrTemporary.value, "row", row.valueName);
  if (attrTemporary.value?.valueName == "") {
    ElMessage.warning("不能为空");

    updateAttr.value!.attrValueList = updateAttr.value!.attrValueList.filter(
      (item) => {
        return item != attrTemporary.value;
        // return item.valueName !== "";
      }
    );
    attrTemporary.value = undefined;
    return;
  }

  const isExist = updateAttr.value!.attrValueList.find(
    (attr) => row.valueName == attr.valueName && attr != attrTemporary.value
  );

  attrTemporary.value = undefined;
  if (isExist) {
    ElMessage.error("重复");
    row.valueName = "";

    attrTemporary.value = row;

    // attrTemporary.value = undefined;
    nextTick(() => {
      valueNameRef.value?.focus();
    });
  }
};
//6、删除
const removeAttr = (row: attrValueListType) => {
  updateAttr.value!.attrValueList = updateAttr.value!.attrValueList.filter(
    (item) => {
      return item != row;
    }
  );
};
</script>
<style scoped></style>
